package com.docios.cookbook2.ui.otherPager;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.docios.cookbook2.databinding.FragmentSearchBinding;
import com.docios.cookbook2.entity.QueryBean;
import com.docios.cookbook2.ui.adapter.ItemCommonFoodAdapter;
import com.docios.cookbook2.ui.adapter.ItemHomeFoodAdapter;
import com.docios.cookbook2.utils.NetUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class SearchFragment extends Fragment {
    FragmentSearchBinding sBinding;
    List<QueryBean> sQueryBeans = new ArrayList<>();
    String start = "0";
    String appcode = "APPCODE 30dd63e48deb4d88b0ffcd5c40c6ae86";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        sBinding = FragmentSearchBinding.inflate(getLayoutInflater());

        initData();
        sBinding.topAppBar.setNavigationOnClickListener(v -> getActivity().finish());
        searchOnClick();

        return sBinding.getRoot();
    }

    private void initData() {
        //显示建议
        //TODO 上拉加载，下拉刷新

        //父activity传的classid
        Bundle bundle=this.getArguments();
        if (bundle!=null){
            aliDataByClassid(bundle.getString("classid"));
        }
    }


    private void searchOnClick() {
        //执行搜索
        sBinding.homeChildSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                // 当用户提交搜索文本时执行的操作
                aliDataByKeyword(query);

                return true;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                // TODO 当搜索文本发生变化时执行的操作 显示提示

                return false;
            }
        });

    }


    /*
     * 阿里云api
     * byKeyword: http://jsucpdq.market.alicloudapi.com/recipe/search?keyword=白菜&num=10&start=1
     * */
    private void aliDataByKeyword(String keyword) {
        Map<String, String> map = new HashMap<>();
        map.put("host", "http://jsucpdq.market.alicloudapi.com/recipe/search?keyword=%s&num=20&start=%s");
        map.put("keyword",keyword);
        map.put("start", start);
        map.put("appcode",appcode);

        NetUtil.queryArrayFromAli(map, new NetUtil.OnArrayQueriedCallBack() {
            @Override
            public void onSuccess(List<QueryBean> recipes) {
                if (getActivity() == null) {
                    return;
                }
                sQueryBeans.clear();
                sQueryBeans.addAll(recipes);
                Log.i("tag########", "onSuccess: " + sQueryBeans);
                //加载卡片
                loadView();
            }

            @Override
            public void onFailure(Exception e) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getActivity(), "网络错误 T~T", Toast.LENGTH_SHORT).show()
                );
            }
        });
        map.clear();

    }


    /*1
     * 《阿里云api》
     * TODO 在设置中添加自定义 appcode
     * byClass 菜谱卡片，分类标签
     * https://jsucpdq.market.alicloudapi.com/recipe/byclass?classid=2&num=10&start=0
     * header
     * */
    private void aliDataByClassid(String classid) {
        Map<String, String> map = new HashMap<>();
        map.put("host", "https://jsucpdq.market.alicloudapi.com/recipe/byclass?classid=%s&num=20&start=%s");
        map.put("classid", classid);
        map.put("start", start);
        map.put("appcode", appcode);

        NetUtil.queryArrayFromAli(map, new NetUtil.OnArrayQueriedCallBack() {
            @Override
            public void onSuccess(List<QueryBean> recipes) {
                if (getActivity() == null) {
                    return;
                }
                sQueryBeans.clear();
                sQueryBeans.addAll(recipes);
                Log.i("tag########", "onSuccess: " + sQueryBeans);
                //加载卡片
                loadView();
            }

            @Override
            public void onFailure(Exception e) {
                if (getActivity() == null) {
                    return;
                }
                getActivity().runOnUiThread(() ->
                        Toast.makeText(getActivity(), "网络错误 T~T", Toast.LENGTH_SHORT).show()
                );
            }
        });
        map.clear();

    }

    /*
     * 菜谱卡片加载
     * */
    public void loadView(){
        Objects.requireNonNull(getActivity()).runOnUiThread(() -> {
            //加入子view
            ItemCommonFoodAdapter adapter = new ItemCommonFoodAdapter(getActivity(), sQueryBeans);
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
            layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

            sBinding.searchRecycle.setLayoutManager(layoutManager);
            sBinding.searchRecycle.setAdapter(adapter);
        });
    }
}
